<template>
  <nav-back title="登录/注册" />
  <van-form @submit="submit" ref="FormInstance">
    <van-cell-group inset>
      <van-field
        center
        label="手机号"
        label-width="50px"
        name="phone"
        v-model="state.phone"
        :rules="[
          {
            pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
            message: '手机号格式有误',
          },
        ]"
      >
        <template #button>
          <van-button
            class="form-btn"
            size="small"
            type="primary"
            loading-text="处理中"
            :loading="state.send.loading"
            :disabled="state.send.disable"
            @click="sendCode"
          >
            {{ state.send.text }}
          </van-button>
        </template>
      </van-field>

      <van-field
        label="验证码"
        label-width="50px"
        name="code"
        v-model="state.code"
        :rules="[{ pattern: /^\d{6}$/, message: '验证码格式有误' }]"
      />
    </van-cell-group>

    <div style="margin: 20px 40px">
      <van-button
        round
        block
        type="primary"
        native-type="submit"
        loading-text="正在处理中..."
        :loading="state.submitLoading"
      >
        立即登录/注册
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import NavBack from "../components/NavBack.vue";
import { onBeforeUnmount, reactive, ref } from "vue";
import { Toast } from "vant";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import api from "../api";
import { store } from "../assets/utils";

const storeVuex = useStore(),
  router = useRouter(),
  route = useRoute();

const FormInstance = ref(null);
let state = reactive({
  phone: "",
  code: "",
  // 控制发送验证码按钮
  send: {
    loading: false,
    disable: false,
    text: "发送验证码",
  },
  submitLoading: false,
});

// 发送验证码
let timer = null;
const sendCode = async () => {
  await FormInstance.value.validate("phone");
  state.send.loading = true;
  let { code } = await api.phoneCode(state.phone);
  if (+code !== 0) {
    Toast.fail("发送失败,请稍后再试~");
    state.send.loading = false;
    return;
  }
  // 发送成功:开启倒计时
  state.send.loading = false;
  state.send.disable = true;
  state.send.text = "30s重发";
  let num = 30;
  timer = setInterval(() => {
    num--;
    if (num <= 0) {
      clearInterval(timer);
      state.send.disable = false;
      state.send.text = `发送验证码`;
      return;
    }
    state.send.text = `${num}s重发`;
  }, 1000);
};
onBeforeUnmount(() => {
  if (timer) clearInterval(timer);
});

// 确认提交:表单校验已经通过
const submit = async () => {
  state.submitLoading = true;
  let { code, token } = await api.login(state.phone, state.code);
  if (+code !== 0) {
    Toast.fail("登录/注册失败~");
    state.submitLoading = false;
    return;
  }
  // 登录成功后要做的事情:存储token & vuex中存储登录者信息 & 提示 & 跳转
  try {
    store.set("tk", token);
    await storeVuex.dispatch("setInfoAsync");
    state.submitLoading = false;
    Toast.success("登录/注册成功~");
    let { from } = route.query;
    from ? router.replace(from) : router.push("/");
  } catch (_) {
    Toast.fail("登录/注册失败~");
    state.submitLoading = false;
  }
};
</script>

<style lang="less" scoped>
.van-form {
  margin-top: 30px;

  .form-btn {
    width: 78px;
  }
}
</style>